import { useEffect } from 'react'
import { isEmpty } from 'project-libs'

let observer: IntersectionObserver
const useLazyImgHook = (ele: string, callback: (v: any) => void, watch: any = []) => {
    useEffect(()=>{
        const doms = document.querySelectorAll(ele)
        if (!isEmpty(doms)) {
            observer = new IntersectionObserver((entries) => {
                callback?.(entries)
                entries.forEach((item)=>{
                    if (item.isIntersecting) {
                        const dataSrc:any = item.target.getAttribute('data-src')
                        item.target.setAttribute('src', dataSrc)
                        observer.unobserve(item.target)
                    }
                })
            })
            doms.forEach((item)=>{
                observer.observe(item)
            })
        }
        return () => {
            if (!isEmpty(doms) && observer) {
                observer.disconnect()
            }
        }
    },watch)
}

export default useLazyImgHook